package com.coffee_shop_app.common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Utils {
    /**
     *  读取指定文件中的数据，将数据读取为byte[]类型
     *  参数：要读取数据的文件路径
     */
    public static byte[] getDataFromFile(File file){
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            // 获取文件的绝对路径
            String absolutePath = file.getAbsolutePath();
            // 创建FileInputStream对象
            fis = new FileInputStream(absolutePath);
            byte[] b = new byte[1024];
            int num =-1;
            bos = new ByteArrayOutputStream();
            while ((num = fis.read(b)) != -1) {
                bos.write(b,0,num);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
